package cn.kgc.crowdfundingadmin.controller;

import cn.kgc.crowdfundingadmin.common.ResultEntity;
import cn.kgc.crowdfundingadmin.pojo.Menu;
import cn.kgc.crowdfundingadmin.service.MenuService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MenuController {

    @Resource
    MenuService menuservice;

    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Menu> getWholeTree(){
             /*查询所有的树型节点用于组装*/
        List<Menu> menuLis=menuservice.getAll();
        //转换为list
        Map<Integer,Menu> menuMap=new HashMap<>();
        for (Menu menu : menuLis) {
            menuMap.put(menu.getId(),menu);
        }

        //声明变量用于存储根节点对象
            //定义根节点
        Menu rootNode=null;
        for (Menu menu : menuLis) {
            //是根节点
            if (menu.getPid()==null){
             rootNode=menu;
             continue;
            }
            menuMap.get(menu.getPid()).getChildren().add(menu);

        }

return  ResultEntity.successWithoutData(rootNode);

    }

//添加
@RequestMapping("/menu/save")
public  ResultEntity<String> savemenu(Menu menu){
menuservice.savaMenu(menu);
return ResultEntity.successWithoutData();
}

//修改回显 result 风格
    @RequestMapping("/menu/get/{menuId}")
public   ResultEntity<Menu> getMenuByid(@PathVariable("menuId") Integer menuId){
Menu menu=menuservice.getMenuById(menuId);
return  ResultEntity.successWithoutData(menu);
    }

    //正式修改
    @RequestMapping("/menu/update")
    public  ResultEntity<String> update(Menu menu){
  menuservice.update(menu);
 return ResultEntity.successWithoutData();

    }

//删除
    @RequestMapping("/menu/delete/{menuId}")
    public ResultEntity<String> delete(@PathVariable Integer  menuId){
menuservice.delete(menuId);
return ResultEntity.successWithoutData();
    }

}
